/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rukopisyimport;

import cz.mzk.rehan.commons.Model;
import java.io.FileNotFoundException;
import org.dom4j.DocumentException;
import rukopisyimport.sourceData.TeiDocument;
import rukopisyimport.sourceData.MarcDocument;
import rukopisyimport.foxml.AbstractPageBuilder;
import rukopisyimport.foxml.MonographBuilder;
import java.io.File;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import rukopisyimport.foxml.InternalPart;
import rukopisyimport.foxml.Page;
import java.util.Collections;
import rukopisyimport.foxml.MonographInternalPartsBuilder;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class ManuscriptConverter {

    private static final Logger logger = Logger.getLogger(ManuscriptConverter.class.getName());
    private final ManuscriptData manuscriptData;
    private final boolean createInternalParts;
    private final File conversionDir;
    private final String monographUuid;
    private final Model model;
    private ConversionLog conversionLog;
    private String monographPid;

    ManuscriptConverter(ManuscriptData manuscriptData, File convertsionRootDir, boolean createInternalParts, String monographUuid, Model model) {
        this.manuscriptData = manuscriptData;
        this.createInternalParts = createInternalParts;
        this.monographUuid = monographUuid;
        this.conversionDir = initConvertedDir(convertsionRootDir);
        this.model = model;
    }

    private File initConvertedDir(File rootDir) {
        File dir = buildConvertedDir(rootDir);
        if (!dir.exists()) {
            dir.mkdirs();
        } else {
            for (File file : dir.listFiles()) {
                file.delete();
            }
        }
        return dir;
    }

    private File buildConvertedDir(File rootDir) {
        String collectionSubDir = manuscriptData.getCollection().getName();
        String mnsDir = manuscriptData.getManuscriptName();
        return new File(rootDir
                + File.separator + collectionSubDir
                + File.separator + mnsDir);
    }

    public void buildFoxmlSet(MonographBuilder monographBuilder, AbstractPageBuilder pageBuilder) throws FileNotFoundException, DocumentException {
        initConversionLog();
        TeiDocument tei = new TeiDocument(manuscriptData.getTeiFile());
        MarcDocument marc = new MarcDocument(manuscriptData.getMarcFile());
        if (!isOk(tei)) {
            return;
        }
        List<Page> pageList = pageBuilder.createPages(conversionDir, tei, marc);
        //printPageList(pageList);
        List<InternalPart> internalPartList = createInternalPartsIfRequired(createInternalParts, tei, pageList);
        createMonograph(monographBuilder, tei, marc, pageList, internalPartList);
        conversionLog.saveToFile();
    }

    private void initConversionLog() {
        conversionLog = new ConversionLog(manuscriptData.getLogFile());
        conversionLog.setCollection(manuscriptData.getCollection());
        conversionLog.setAlephBase("MZK03");//TODO
        conversionLog.setInImageServer(manuscriptData.isInImageServer());
        conversionLog.logDataSources(manuscriptData);
    }

    private boolean isOk(TeiDocument tei) {
        if (tei.getDocument() == null) {
            logger.log(Level.SEVERE, "Cannot parse xml file ''{0}''", manuscriptData.getTeiFile().getAbsolutePath());
            return false;
        }
        if (tei.findSignature() == null) {
            logger.log(Level.SEVERE, "No signature found for file ''{0}''", manuscriptData.getTeiFile().getAbsolutePath());
            return false;
        }
        return true;
    }

    private List<InternalPart> createInternalPartsIfRequired(boolean createInternalParts, TeiDocument tei, List<Page> pageList) {
        if (createInternalParts) {
            MonographInternalPartsBuilder builder = new MonographInternalPartsBuilder(conversionDir, tei, pageList);
            return builder.createInternalParts();
        } else {
            return Collections.<InternalPart>emptyList();
        }
    }

    private void createMonograph(MonographBuilder monographBuilder, TeiDocument tei, MarcDocument marc, List<Page> pageList, List<InternalPart> internalPartList) throws FileNotFoundException, DocumentException {
        MonographData data = new MonographData();
        data.setCollection(manuscriptData.getCollection());
        data.setConversionDir(conversionDir);
        data.setInternalPartList(internalPartList);
        data.setMarc(marc);
        data.setPageList(pageList);
        data.setTei(tei);
        monographPid = monographBuilder.createAndSaveMonograph(data, conversionLog, monographUuid, model);
    }

    /**
     * @return the monographPid
     */
    public String getMonographPid() {
        return monographPid;
    }

    private void printPageList(List<Page> pageList) {
        for (Page page : pageList) {
            System.out.println("page.id: " + page.getId());
            System.out.println("page.label: " + page.getLabel());
        }
    }
}
